package org.rpgmapper.adapter;

import java.util.List;

import org.rpgmapper.R;
import org.rpgmapper.bo.Character;
import org.rpgmapper.database.RPGMapperOpenHelper;

import android.app.AlertDialog;
import android.content.ClipData;
import android.content.ClipDescription;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.view.DragEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;

public class PCSidesAdapter extends BaseAdapter {

    private List<Character> pcs;
    private Context context;
    private LayoutInflater inflater;
    private Character selectedCharacter;
    private EditText editTextName;

    public PCSidesAdapter(Context context) {
        this.context = context;
        this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        RPGMapperOpenHelper helper = new RPGMapperOpenHelper(context);
        this.pcs = helper.getAllHeroes();
    }

    public int getCount() {
        return pcs.size();
    }

    public Object getItem(int position) {
        return pcs.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewGroup view;
        if (convertView == null) {
            view = (ViewGroup) inflater.inflate(R.layout.unknown_character, null);//new TextView(context);
        } else {
            view = (ViewGroup) convertView;
        }
        Character c = pcs.get(position);
        view.setTag(c);
        ((TextView) view.findViewById(R.id.name)).setText(c.getName());
        //glView.setOnTouchListener(onTouchDragListener);
        view.setOnClickListener(onClickListener);
        view.setOnLongClickListener(onLongClickListener);
        view.setOnDragListener(new OnDragPCListener());
        return view;
    }
    private OnClickListener onClickListener = new OnClickListener() {

        public void onClick(View v) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);

            View layout = PCSidesAdapter.this.inflater.inflate(R.layout.character_dialog, null);

            selectedCharacter = (Character) v.getTag();
            editTextName = (EditText) layout.findViewById(R.id.name);
            editTextName.setText(selectedCharacter.getName());

            builder.setView(layout).setPositiveButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    RPGMapperOpenHelper helper = new RPGMapperOpenHelper(context);
                    selectedCharacter.setName(editTextName.getText().toString());
                    helper.updateCharacter(selectedCharacter);
                    //((PlacePlayersActivity)context).invalidateCharacters();
                    List<Character> chars = helper.getAllHeroes();
                    for (Character character : chars) {
                        System.err.println(character.toString());
                    }
                }
            }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.create().show();
        }
    };
    private OnTouchListener onTouchDragListener = new OnTouchListener() {

        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                final CharSequence text = "" + ((Character) v.getTag()).getId();
                ClipData.Item item = new ClipData.Item(text);
                ClipData dragData = new ClipData(text, new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}, item);
                MyDragShadowBuilder myShadow = new MyDragShadowBuilder(v);
                //DragShadowBuilder myShadow = new DragShadowBuilder(v);
                v.startDrag(dragData, // the data to be dragged
                        myShadow, // the drag shadow builder
                        null, // no need to use local data
                        0 // flags (not currently used, set to 0)
                        );
                return true;
            }
            return false;
        }
    };
    private OnLongClickListener onLongClickListener = new OnLongClickListener() {

        public boolean onLongClick(View v) {
            final ViewGroup vg = (ViewGroup) v;
            final CharSequence text = "" + ((Character) v.getTag()).getId();
            ClipData.Item item = new ClipData.Item(text);
            ClipData dragData = new ClipData(text, new String[]{ClipDescription.MIMETYPE_TEXT_PLAIN}, item);
            MyDragShadowBuilder myShadow = new MyDragShadowBuilder(v);
            //DragShadowBuilder myShadow = new DragShadowBuilder(v);
            v.startDrag(dragData, // the data to be dragged
                    myShadow, // the drag shadow builder
                    null, // no need to use local data
                    0 // flags (not currently used, set to 0)
                    );

            return true;
        }
    };

    private class OnDragPCListener implements View.OnDragListener {

        public boolean onDrag(View v, DragEvent event) {
            // Defines a variable to store the action type for the incoming event
            final int action = event.getAction();
            // Handles each of the expected events
            switch (action) {
                case DragEvent.ACTION_DRAG_STARTED:
                    v.setAlpha(0.5f);
                    return false;
                case DragEvent.ACTION_DRAG_ENDED:
                    v.setAlpha(1f);
                    return (true);
                // An unknown action type was received.
                default:
                    //Log.e("DragDrop Example","Unknown action type received by OnDragListener.");
                    break;
            };
            return false;
        }
    }

    private class MyDragShadowBuilder extends View.DragShadowBuilder {
        // The drag shadow image, defined as a drawable thing

        private Drawable shadow = PCSidesAdapter.this.context.getResources().getDrawable(R.drawable.ic_contact_picture);

        // Defines the constructor for myDragShadowBuilder
        public MyDragShadowBuilder(View v) {
            // Stores the View parameter passed to myDragShadowBuilder.
            super(v);
            // Creates a draggable image that will fill the Canvas provided by the system.
            //shadow = new ColorDrawable(Color.RED);
        }

        // Defines a callback that sends the drag shadow dimensions and touch point back to the
        // system.
        @Override
        public void onProvideShadowMetrics(Point size, Point touch) {
            // Defines local variables
            int width, height;

            // Sets the width of the shadow to the width of the original View
            width = shadow.getIntrinsicWidth();//getView().getWidth();// / 2;

            // Sets the height of the shadow to the height of the original View
            height = shadow.getIntrinsicHeight();//getView().getHeight();// / 2;

            // The drag shadow is a ColorDrawable. This sets its dimensions to be the same as the
            // Canvas that the system will provide. As a result, the drag shadow will fill the
            // Canvas.
            shadow.setBounds(0, 0, width, height);

            // Sets the size parameter's width and height values. These get back to the system
            // through the size parameter.
            size.set(width, height);

            // Sets the touch point's position to be in the middle of the drag shadow
            touch.set(width / 2, height / 2);
        }

        // Defines a callback that draws the drag shadow in a Canvas that the system constructs
        // from the dimensions passed in onProvideShadowMetrics().
        public void onDrawShadow(Canvas canvas) {
            // Draws the ColorDrawable in the Canvas passed in from the system.
            shadow.draw(canvas);
        }
    }
}
